
package com.hfh.main.group.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hfh.main.common.annotate.JwtToken;
import com.hfh.main.common.resp.Result;
import com.hfh.main.course.entity.CourseListEntity;
import com.hfh.main.course.service.CourseListService;
import com.hfh.main.group.entity.GroupDetailEntity;
import com.hfh.main.group.entity.GroupEntity;
import com.hfh.main.group.mapper.GroupDetailMapper;
import com.hfh.main.group.service.GroupDetailService;
import com.hfh.main.group.service.GroupService;
import com.hfh.main.report.entity.WeekEntity;
import com.hfh.main.report.service.WeekService;
import com.hfh.main.user.entity.UserEntity;
import com.hfh.main.user.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Tag(name = "分组管理")
@RestController
@RequestMapping("/groupDetailEntity")
public class GroupDetailController {

    @Autowired
    private GroupDetailMapper groupDetailMapper;
    @Autowired
    private GroupDetailService groupDetailService;
    @Autowired
    private UserService userService;
    @Autowired
    private GroupService groupService;
    @Autowired
    private CourseListService courseListService;
    @Autowired
    private WeekService weekService;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

//    @JwtToken
//    @Operation(summary = "列表-分页")
//    @PostMapping("/listPageGroup")
//    public Result<?> listPageGroupList(@RequestParam Integer page, @RequestParam Integer pageSize) {
//        //分页参数
//        Page<GroupDetailEntity> rowPage = new Page(page, pageSize);
//        //queryWrapper组装查询where条件
//        LambdaQueryWrapper<GroupDetailEntity> queryWrapper = new LambdaQueryWrapper<>();
//        rowPage = groupDetailMapper.selectPage(rowPage, queryWrapper);
//        return Result.success("数据请求成功", rowPage);
//    }

    @JwtToken
    @Operation(summary = "组明细-根据ID或者学号查询")
    @PostMapping("/selectGroupByID/{param}")
    public Result<?> selectGroupByID(@PathVariable @Validated String param) {
        if (param.contains("ZF")) {
            QueryWrapper<GroupEntity> wrapper = new QueryWrapper<>();
            wrapper.eq(("user_acc"), param);
            GroupEntity one = groupService.getOne(wrapper);
            param = one.getId() + "";
        }
        QueryWrapper<GroupDetailEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(("group_id"), Integer.parseInt(param));
        return Result.success(supplementList(groupDetailService.list(wrapper)));
    }

//    @JwtToken
//    @Operation(summary = "组明细-根据组长学号查询组员")
//    @PostMapping("/selectGroupByLeaderAcc/{param}")
//    public Result<?> selectGroupByLeaderAcc(@PathVariable @Validated String param) {
//        LambdaQueryWrapper<GroupEntity> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(GroupEntity::getAcc, param);
//        GroupEntity one = groupService.getOne(wrapper);
//        Integer id = one.getId();
//        QueryWrapper<GroupDetailEntity> wrapper2 = new QueryWrapper<>();
//        wrapper2.eq("group_id", id);
//        if (groupDetailService.count(wrapper2) == 0) return Result.failure(500, "编号不存在", sdf.format(new Date()));
//        return Result.success(supplementList(groupDetailService.list(wrapper2)));
//    }

    @JwtToken
    @Operation(summary = "组明细-添加组员")
    @PostMapping("/insert")
    public Result<?> insertGroup(@RequestBody @Validated GroupDetailEntity entity) {
        QueryWrapper<GroupDetailEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("user_acc", entity.getAcc());
        //查看是否已分组
        List<GroupDetailEntity> list = groupDetailService.list(wrapper);
        //如果不为空则 该用户已被分组
        if (list.size() != 0) return Result.failure(500, "该用户已被分组", sdf.format(new Date()));

        //拿到组信息
        GroupEntity groupEntity = groupService.getById(entity.getGroupId());
        //添加组员的时候往 week周表中添加5条数据
        addOneGroupDataForWeek(groupEntity.getGroupNo());

        if (groupDetailService.save(entity)) return Result.success("保存成功", sdf.format(new Date()));
        return Result.failure(500, "保存失败", sdf.format(new Date()));
    }

    /**
     * 给week周表补充某个组中缺失的组员week数据
     */
    public void addOneGroupDataForWeek(String groupNo){
        //拿到组信息
        GroupEntity groupEntity = groupService.getOne(new QueryWrapper<GroupEntity>().eq("group_no", groupNo));
        //拿到项目信息
        CourseListEntity courseListEntity = courseListService.getOne(new QueryWrapper<CourseListEntity>().eq("list_id", groupEntity.getListId()));
        String startDate = dateFormat.format(courseListEntity.getStartDate());
        Integer start_year = Integer.valueOf(startDate.toString().substring(0, 4));
        Integer start_month = Integer.valueOf(startDate.toString().substring(5, 7));
        //查某组明细
        QueryWrapper<GroupDetailEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("group_id", groupEntity.getId());
        List<GroupDetailEntity> groupDetailEntityList = groupDetailService.list(wrapper);

        //找到groupDetailEntityList中的且不在周表中的组员
        for(GroupDetailEntity entity : groupDetailEntityList){
            QueryWrapper<WeekEntity> wrapper2 = new QueryWrapper<>();
            wrapper2.eq("user_acc", entity.getAcc());
            if (weekService.count(wrapper2) == 0) {
                //添加组员的时候往 week周表中添加4条数据 问就是只有4周
                for(int i = 1; i <= 4; i++){
                    WeekEntity weekEntity = new WeekEntity();
                    weekEntity.setAcc(entity.getAcc()); //设置这个组员的周表
                    weekEntity.setYear(start_year);
                    weekEntity.setMonth(start_month);
                    weekEntity.setWeekNumber(i);
                    weekService.save(weekEntity);
                }
            }
        }


    }



    @JwtToken
    @Operation(summary = "组明细-删除组员")
    @PostMapping("/delete/{param}")
    public Result<?> deleteGroup(@PathVariable @Validated String param) {
        QueryWrapper<GroupDetailEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(("id"), param);
        if (groupDetailService.count(wrapper) == 0) return Result.failure(500, "编号不存在", sdf.format(new Date()));
        //通过传入的编号查询
        GroupDetailEntity detail = groupDetailService.getOne(wrapper);
        //查询所有组长
        QueryWrapper<UserEntity> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("user_role", 2); // 角色组长
        List<UserEntity> uList = userService.list(wrapper2);
        //如果要删的组员属于组长则不能删除
        for (UserEntity user : uList) {
            if (user.getAcc().equals(detail.getAcc())) return Result.failure(500, "该组员是组长，不能删除", sdf.format(new Date()));
        }
        //TODO
        //删除组员时，删除该组员的周表
        if (groupDetailService.remove(wrapper)) return Result.success("删除成功", sdf.format(new Date()));
        return Result.failure(500, "删除失败", sdf.format(new Date()));
    }

    @JwtToken
    @Operation(summary = "组明细-根据id修改")
    @PostMapping("/update")
    public Result<?> updateGroup(@RequestBody @Validated GroupDetailEntity entity) {
        QueryWrapper<GroupDetailEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(("id"), entity.getId());
        if (groupDetailService.count(wrapper) == 0) return Result.failure(500, "编号不存在", sdf.format(new Date()));
        if (groupDetailService.updateById(entity)
                //鉴于角色是取的用户表，这里把用户表也改一下吧
            && userService.updateUserByAcc(new UserEntity().setAcc(entity.getAcc()).setIdentity(entity.getIdentity()))
        ) return Result.success("修改成功", sdf.format(new Date()));
        return Result.failure(500, "修改失败", sdf.format(new Date()));
    }

    /**
     * 字段补充
     *
     * @param entity
     * @return
     */
    public GroupDetailEntity supplement(GroupDetailEntity entity) {
        String acc = entity.getAcc();
        UserEntity userEntity = userService.queryByAcc(acc);
        String name = userEntity.getName();
        String identity = userEntity.getIdentity();
        String phone = userEntity.getPhone();
        entity.setName(name);
        entity.setIdentity(identity);
        entity.setPhone(phone);
        return entity;
    }

    /**
     * 字段补充
     *
     * @param entitys
     * @return
     */
    public List<GroupDetailEntity> supplementList(@NotNull List<GroupDetailEntity> entitys) {
        List<GroupDetailEntity> collect = entitys.stream().map(entity -> {
            String acc = entity.getAcc();
            UserEntity userEntity = userService.queryByAcc(acc);
            String name = userEntity.getName();
            String identity = userEntity.getIdentity();
            String phone = userEntity.getPhone();
            entity.setName(name);
            entity.setIdentity(identity);
            entity.setPhone(phone);
            String df = "0";
            if(userEntity.getDbFinal()>=100){
                df = "100"; //超100分只展示100
            }else if(userEntity.getDbFinal() == 0){
                df = "-";
            }else {
                df = userEntity.getDbFinal()+"";
            }
            entity.setDbFinal(df);
            return entity;
        }).toList();
        return collect;
    }

}
